package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.page.PageBean;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.qbdms.consts.HighlightConst;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.model.WQbdMyCollection;
import com.ccp.dev.qbdms.model.WQbdQualityKnow;
import com.ccp.dev.qbdms.service.WQbdMyCollectionService;
import com.ccp.dev.qbdms.service.WQbdMyPushRecordService;
import com.ccp.dev.qbdms.service.WQbdQualityKnowService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import java.io.PrintWriter;

import com.ccp.dev.system.service.DictionaryService;
import io.netty.util.internal.ObjectUtil;
import net.sf.json.JSONObject;
import java.nio.charset.StandardCharsets;
import com.ccp.dev.qbdms.model.WQbdMyKnowledge;
import com.ccp.dev.qbdms.service.WQbdMyKnowledgeService;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;
import java.util.ArrayList;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 我的知识 信息操作处理控制器
 * 
 * @author hw
 * @date 2020-07-27 10:56:30
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "我的知识")
@RequestMapping("/qbdms/wQbdMyKnowledge")
public class WQbdMyKnowledgeController extends SysBaseController{
	@Resource
	private WQbdMyKnowledgeService wQbdMyKnowledgeService;
    @Resource
    WQbdQualityKnowService wQbdQualityKnowService;
    @Resource
    WQbdMyCollectionService wQbdMyCollectionService;
    @Resource
    DictionaryService dictionaryService;
    @Resource
    WQbdMyPushRecordService wQbdMyPushRecordService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2020-07-27 10:56:30
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到我的知识首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request,ModelMap modelMap) {
        String tab = RequestUtil.getString(request,"tab");
        modelMap.put("tab",tab);
        return "wQbdMyKnowledge/list";
    }
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/messageList")
    @Action(description="跳转到我的知识首页", exectype = "页面跳转日志")
    public String viewLists() {
        return "wQbdMyKnowledge/messageList";
    }

    /**
    * 功能描述:我的收藏
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-27 10:56:30
    */
    @RequestMapping("/collection"+UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="我的收藏",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object collectionlist(HttpServletRequest request,ModelMap modelMap ) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        ZhiLiangConst.addQueryFilter(queryFilter);
        queryFilter.remove("belongdeptname");
        queryFilter.addFilter("belongdeptname", BaseUtil.getCurrentTenOrgCodePath());

        //分页数据
//        List<WQbdQualityKnow> pageDatas = wQbdQualityKnowService.queryList(queryFilter);
        queryFilter.addFilter("userId",ContextUtil.getCurrentUserId());
        List<WQbdQualityKnow> pageDatas = wQbdQualityKnowService.queryByCollectionList(queryFilter);
//        List<WQbdQualityKnow> pageDatas = wQbdQualityKnowService.queryES(queryFilter);


        String userId=ContextUtil.getCurrentUserId();
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey("mj", false);
        if(BeanUtils.isNotEmpty(pageDatas)){
        pageDatas.forEach(wQbdQualityKnow->{
//            wQbdQualityKnow.setEnclosure( wQbdQualityKnow.getSummaryDocument());
            //密级回显
            dicList.forEach(dictionary -> {
                if(dictionary.getItemValue().equals(wQbdQualityKnow.getSecret())){
                    wQbdQualityKnow.setSecret(dictionary.getItemName());
                }
            });
            String enclosure = wQbdQualityKnow.getEnclosure();
            enclosure =enclosure.substring(1,enclosure.length()-1);
            Map<String,Object> parse = JSON.parseObject(enclosure);
            String fileId = parse.get("fileId").toString();
            wQbdQualityKnow.setFileId(fileId);
//            WQbdMyCollection wQbdMyCollection = wQbdMyCollectionService.queryIsSc(userId, wQbdQualityKnow.getId());
//            if (ObjectUtils.isEmpty(wQbdMyCollection)){
//                wQbdQualityKnow.setCollectionStatus(HighlightConst.COLLECTION__MAP.get(HighlightConst.COLLECTION_NO));
//            }else {
//                wQbdQualityKnow.setCollectionStatus(wQbdMyCollection.getStatus());
//                if (wQbdMyCollection.getStatus().equals(HighlightConst.COLLECTION__MAP.get(HighlightConst.COLLECTION_YES))){
//                    pageDatasGz.add(wQbdQualityKnow);
//                }
//            }
        });}
        SysAuditThreadLocalHolder.putParamerter("success",true);
        modelMap.put("tab","mysc");
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述:我的关注
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2020-07-27 10:56:30
     */
    @RequestMapping("/messageList")
    @ResponseBody
    @Action(description="我的关注",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object messageList(HttpServletRequest request,ModelMap modelMap) {
        QueryFilter queryFilter = new QueryFilter(request, false);
        //分页数据
        List<WQbdQualityKnow> pageDatas = wQbdQualityKnowService.queryUnread(queryFilter);
        List<WQbdQualityKnow> pageDatasGz=new ArrayList<>();
        String userId=ContextUtil.getCurrentUserId();
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey("mj", false);
        pageDatas.forEach(wQbdQualityKnow->{
            //密级回显
            dicList.forEach(dictionary -> {
                if(dictionary.getItemValue().equals(wQbdQualityKnow.getSecret())){
                    wQbdQualityKnow.setSecret(dictionary.getItemName());
                }
            });
            String enclosure = wQbdQualityKnow.getEnclosure();
            enclosure =enclosure.substring(1,enclosure.length()-1);
            Map<String,Object> parse = JSON.parseObject(enclosure);
            String fileId = parse.get("fileId").toString();
            wQbdQualityKnow.setFileId(fileId);
            WQbdMyCollection wQbdMyCollection = wQbdMyCollectionService.queryIsSc(userId, wQbdQualityKnow.getId());
            if (ObjectUtils.isEmpty(wQbdMyCollection)){
                wQbdQualityKnow.setCollectionStatus(HighlightConst.COLLECTION__MAP.get(HighlightConst.COLLECTION_NO));
            }else {
                wQbdQualityKnow.setCollectionStatus(wQbdMyCollection.getStatus());
                if (wQbdMyCollection.getStatus().equals(HighlightConst.COLLECTION__MAP.get(HighlightConst.COLLECTION_YES))){
                    pageDatasGz.add(wQbdQualityKnow);
                }
            }
        });
        modelMap.put("tab","mygz");
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",pageDatas);
    }



    /**
     * 功能描述:我的关注
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2020-07-27 10:56:30
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="我的关注",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object focuslist(HttpServletRequest request,ModelMap modelMap) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        ZhiLiangConst.addQueryFilter(queryFilter);
        queryFilter.remove("belongdeptname");
        queryFilter.addFilter("belongdeptname", BaseUtil.getCurrentTenOrgCodePath());

        List<WQbdMyKnowledge> wQbdMyKnowledges = wQbdMyKnowledgeService.findByUserId(ContextUtil.getCurrentUserId());
        List<String> knowedgeClass=new ArrayList();
        if (BeanUtils.isNotEmpty(wQbdMyKnowledges)){
            wQbdMyKnowledges.forEach(wQbdMyKnowledge -> {
                String knowledge_classifica = wQbdMyKnowledge.getKnowledge_classifica();
                knowedgeClass.add(knowledge_classifica);
            });
        }
        queryFilter.addFilter("knowedgeClass",knowedgeClass);
        if (BeanUtils.isEmpty(knowedgeClass)){
            return success(null, 0);
        }
        List<WQbdQualityKnow> pageDatas = wQbdQualityKnowService.queryES(queryFilter);
        int count = wQbdQualityKnowService.queryESCount(queryFilter);
        String userId=ContextUtil.getCurrentUserId();
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey("mj", false);
        if (BeanUtils.isNotEmpty(pageDatas)){
        pageDatas.forEach(wQbdQualityKnow->{
            //密级回显
            dicList.forEach(dictionary -> {
                if(dictionary.getItemValue().equals(wQbdQualityKnow.getSecret())){
                    wQbdQualityKnow.setSecret(dictionary.getItemName());
                }
            });
            String enclosure = wQbdQualityKnow.getEnclosure();
            enclosure =enclosure.substring(1,enclosure.length()-1);
            Map<String,Object> parse = JSON.parseObject(enclosure);
            String fileId = parse.get("fileId").toString();
            wQbdQualityKnow.setFileId(fileId);
            WQbdMyCollection wQbdMyCollection = wQbdMyCollectionService.queryIsSc(userId, wQbdQualityKnow.getId());
            if (ObjectUtils.isEmpty(wQbdMyCollection)){
                wQbdQualityKnow.setCollectionStatus(HighlightConst.COLLECTION__MAP.get(HighlightConst.COLLECTION_NO));
            }else {
                wQbdQualityKnow.setCollectionStatus(wQbdMyCollection.getStatus());
            }

        });}
        SysAuditThreadLocalHolder.putParamerter("success",true);
        modelMap.put("tab","mygz");
        return success(pageDatas, count);
    }

    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2020-07-27 10:56:30
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到我的知识新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        return "wQbdMyKnowledge/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdMyKnowledge 保存的对象
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-27 10:56:30
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存我的知识数据",detail="<#if isAdd>新增<#else>编辑</#if>我的知识数据<#if success>成功<#else>失败</#if>")
    public Object save(@RequestParam(value = "knowledge_classifica") String knowledge_classifica) {
        int result;
        String userId=ContextUtil.getCurrentUserId();
        WQbdMyKnowledge wQbdMyKnowledge=wQbdMyKnowledgeService.findByUserIdAndknowClassId(knowledge_classifica,userId);
        if (BeanUtils.isNotEmpty(wQbdMyKnowledge)){
            result = wQbdMyKnowledgeService.delByUserIdAndDicId(userId,knowledge_classifica);
        }else{
            WQbdMyKnowledge wQbdMyKnowledge1=new WQbdMyKnowledge();
            wQbdMyKnowledge1.setId(UUIDUtils.getUUIDFor32());
            wQbdMyKnowledge1.setCreateTime(new Date());
            wQbdMyKnowledge1.setUser_id(userId);
            wQbdMyKnowledge1.setCreateBy(userId);
            wQbdMyKnowledge1.setKnowledge_classifica(knowledge_classifica);
            result = wQbdMyKnowledgeService.add(wQbdMyKnowledge1);
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2020-07-27 10:56:30
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到我的知识详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        String tab = RequestUtil.getString(request,"tab");
        modelMap.put("tab",tab);
        modelMap.put("id",id);

        String popupRemindData = RequestUtil.getString(request,"isPopupRemindData");
        if(StringUtil.isNotEmpty(popupRemindData)){
            String userId = ContextUtil.getCurrentUser().getUserId();
            wQbdMyPushRecordService.updateStatusByData(userId,id);
            modelMap.put("popupRemindData",popupRemindData);
        }

        WQbdQualityKnow wQbdQualityKnow = wQbdQualityKnowService.getOneById(id);
        String enclosure = wQbdQualityKnow.getEnclosure();
        enclosure =enclosure.substring(1,enclosure.length()-1);
        Map<String,Object> parse = JSON.parseObject(enclosure);
        String fileId = parse.get("fileId").toString();
        wQbdQualityKnow.setFileId(fileId);
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey("mj", false);
        dicList.forEach(dic->{
            if( dic.getItemValue().equals(wQbdQualityKnow.getSecret())){
                wQbdQualityKnow.setSecret(dic.getItemName());
            }
        });

        wQbdQualityKnow.getSecret();
        modelMap.put("wQbdQualityKnow",wQbdQualityKnow);
        return "wQbdMyKnowledge/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-27 10:56:30
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询我的知识的一条数据",detail="根据主键id查询我的知识的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdMyKnowledge wQbdMyKnowledge = wQbdMyKnowledgeService.getOneById(id);
        if (null == wQbdMyKnowledge) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdMyKnowledge);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-27 10:56:30
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除我的知识数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = wQbdMyKnowledgeService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }
    /**
     * 功能描述: 获取我的知识分类字典数据
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-07-20 10:41:54
     */
    @RequestMapping("/getKnowDic")
    @ResponseBody
    @Action(description="获取我的知识分类字典数据",detail="获取我的知识分类字典数据<#if success>成功<#else></#if>")
    public Object getKnowDic(HttpServletRequest request,ModelMap modelMap) {
        Map<String, Object> zsfl1 = dictionaryService.getTreeDicByNodeKey("zsfl1");
        QueryFilter queryFilter=new QueryFilter(request);
        queryFilter.addFilter("user_id",ContextUtil.getCurrentUserId());
        List<WQbdMyKnowledge> wQbdMyKnowledgeList = wQbdMyKnowledgeService.queryList(queryFilter);
        modelMap.put("tab","sz");
        zsfl1.put("myDicList",wQbdMyKnowledgeList);
        return  zsfl1;
    }
    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到我的知识导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdMyKnowledge/import";
    }

    /**
    * 功能描述: 导出我的知识数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: hw
    * @date: 2020-07-27 10:56:30
    */
    @RequestMapping("/exportData")
    @Action(description="导出我的知识数据信息",detail="导出我的知识数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String[] id = RequestUtil.getStringAryByStr(request,"id");
        QueryFilter queryFilter = new QueryFilter(request,false);
        if(BeanUtils.isNotEmpty(id) && id.length!=0){
            queryFilter.put("byId",true);
            queryFilter.put("id",id);
        }else{
            queryFilter.put("byId",false);
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        Excel excel = new Excel();
        String fileName = "WQbdMyKnowledge";//导出的文件名称
        excel.sheet().sheetName("sheet");// 重命名当前处于工作状态的表的名称
        List<String> titleList = new ArrayList<>();
        titleList.add("主键");
        titleList.add("知识分类1");
        titleList.add("用户id");
        titleList.add("租户Id");
        titleList.add("创建人");
        titleList.add("创建时间");
        titleList.add("更新人");
        titleList.add("更新时间");
        titleList.add("密级");
        excel.row(0, 0).value(titleList.toArray());
        excel.row(0,0).font(new IFontEditor() {
            // 设置字体
            @Override
            public void updateFont(Font font) {
                font.boldweight(BoldWeight.BOLD);// 粗体
            }
        }).bgColor(Color.GREY_25_PERCENT).width(3500);
        excel.row(0, 1).width(3500);
        excel.row(0, 2).width(3500);
        excel.row(0, 3).width(3500);
        excel.row(0, 4).width(3500);
        //设置列的数据格式
        excel.sheet().setDefaultColumnStyle(0, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(1, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(2, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(3, DataFormat.TEXT);
        ExcelUtil.downloadExcel(wQbdMyKnowledgeService.exportExcel(excel,queryFilter), fileName, response);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    public void importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        MultipartFile multipartFile = request.getFile("file");
        PrintWriter writer = response.getWriter();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //读取excel文件，并获取每行的数据
            ExcelReader excelReader = new ExcelReader();
            TableEntity excelEntity = excelReader.readFile(multipartFile.getInputStream());
            List<DataEntity> rowDataEntityList = excelEntity.getDataEntityList();

            List<WQbdMyKnowledge> listToInsert = new ArrayList<>();
            for (DataEntity dataEntity : rowDataEntityList) {
                //获取每列的数据
                List<FieldEntity> fieldEntityList = dataEntity.getFieldEntityList();
                WQbdMyKnowledge dataToInsert = new WQbdMyKnowledge();
                int i =0;
                //根据列的顺序，给相应的对象赋值
                for (FieldEntity fieldEntity : fieldEntityList) {
                    //if(i==0){
                        //dataToInsert.setName(fieldEntity.getValue());
                    //}
                    i++;
                }
                dataToInsert.setId(UUIDUtils.getUUIDFor32());
                listToInsert.add(dataToInsert);
            }
            wQbdMyKnowledgeService.addList(listToInsert);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("operation.success"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        }
    }


}
